var AddPayModeForm = function () {
  var template = /* html */ `
    <div>
      <el-input v-model="payMode" size="small" style="width:100%" placeholder="请输入要添加的收付款方式"></el-input>
      <div style="text-align:center;margin-top:10px;">
        <el-button size="small" type="primary" @click="ensure">确定</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      payModeList: {
        type: Array,
        default: function () {
          return [];
        }
      }
    },

    data: function () {
      return {
        payMode: ''
      };
    },

    methods: {
      ensure: function () {
        var payMode = this.payMode;
        if (payMode === '') {
          this.$alert('请输入付款方式', '信息');
          return;
        }

        var payModeList = this.payModeList;
        if (payModeList.indexOf(payMode) !== -1) {
          this.$alert('所添加的付款方式已存在，不能再添加', '信息');
          return;
        }
        this.$emit('add-mode', payMode);
        this.payMode = '';
      }
    },

    template: template
  };
}();

var CostOrder = function () {
  var CostOrderForm = function () {
    BaseModel.call(this);

    var self = this;
    var fn = {
      initData: function () {
        self.type = ''; //1收款 2付款
        self.reason = '';
        self.receiptPaymentMode = '';
        self.payPrice = undefined;
        self.customerName = '';
        self.relationBank = '';
        self.invoicePrice = undefined;
        self.invoiceDate = null;
        self.actualDay = moment().valueOf();
      }
    };

    this.clearInfo = function () {
      self.reason = '';
      self.receiptPaymentMode = '';
      self.payPrice = undefined;
      self.customerName = '';
      self.relationBank = '';
      self.invoicePrice = undefined;
      self.invoiceDate = null;
      self.actualDay = moment().valueOf();
    };

    this.checkValid = function () {
      var fields = ['type', 'payPrice', 'receiptPaymentMode', 'customerName', 'relationBank'];
      var code = this.checkRequiredFields(fields);
      if (code !== '') {
        return code;
      }
      if (this.payPrice === 0) {
        return 'payPriceZero';
      }

      var invoicePrice = this.invoicePrice;
      var invoiceDate = this.invoiceDate;
      if (!SysUtil.isEmpty(invoicePrice) || !SysUtil.isEmpty(invoiceDate)) {
        if (invoicePrice === undefined) {
          return 'invoicePrice';
        }
        if (invoiceDate === null) {
          return 'invoiceDate';
        }
      }
      return '';
    };

    this.getObject = function (payType) {
      var postData = {
        payType: payType,
        source: 3,
        sumMoney: this.payPrice
      };
      var fields = ['type', 'reason', 'receiptPaymentMode', 'customerName', 'relationBank'];
      this.setPostData(postData, fields);

      var invoicePrice = this.invoicePrice;
      var invoiceDate = this.invoiceDate;
      if (!SysUtil.isEmpty(invoicePrice) && !SysUtil.isEmpty(invoiceDate)) {
        postData.invoicePrice = invoicePrice;
        postData.invoiceDate = moment(invoiceDate).format('YYYY-MM-DD');
      }

      var actualDay = this.actualDay;
      if (!SysUtil.isEmpty(actualDay)) {
        postData.actualDay = moment(actualDay).format('YYYY-MM-DD HH:mm:ss');
      }

      return postData;
    };

    fn.initData();
  };

  var template = /* html */ `
    <div class="cost-order" v-loading.fullscreen.lock="loading">
      <el-form label-width="auto">
        <el-form-item required label="收付款类型">
          <el-select class="cost-input" v-model="costOrderForm.type" @change="clearInfo">
            <el-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <template v-if="costOrderForm.type!==''">
          <el-form-item required :label="costTypeText+'金额'">
            <el-input-number is-decimal-zero v-model="costOrderForm.payPrice" class="cost-input" :min="0" :precision="4" :controls="false" :placeholder="'请输入'+costTypeText+'金额'">
            </el-input-number>
          </el-form-item>
          <el-form-item required :label="costTypeText+'方式'">
            <el-select filterable v-model="costOrderForm.receiptPaymentMode" :placeholder="'请输入'+costTypeText+'方式'" style="width:calc(100% - 120px)">
              <el-option v-for="payMode in payModeList" :key="'payMode_'+payMode" :value="payMode">
              </el-option>
            </el-select>
            <el-popover v-model="showAddPayModeForm" trigger="click" width="200" style="margin-left:15px">
              <el-button slot="reference" type="primary">添加方式</el-button>
              <add-pay-mode-form :pay-mode-list="payModeList" @add-mode="addPayMode"></add-pay-mode-form>
            </el-popover>
          </el-form-item>
          <el-form-item required :label="costCustomerTypeText+'方'" :placeholder="'请输入'+costCustomerTypeText+'方'">
            <el-select filterable v-model="costOrderForm.customerName" class="cost-input">
              <template v-if="costOrderForm.type===1">
                <el-option v-for="name in customerNameList" :key="name" :value="name"></el-option>
              </template>
              <template v-else>
                <el-option v-for="name in providerNameList" :key="name" :value="name"></el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item required label="银行卡号">
            <filter-select filterable v-model="costOrderForm.relationBank" class="cost-input" :options="bankCardList" value-field="num" label-field="num"
              placeholder="请选择银行卡号" :filter-method="cardFilterMehod">
              <template slot="item" slot-scope="scope">
                <div class="clearfix">
                  <span>{{scope.option.num}}</span>
                  <span style="float:right;color:#8492a6;margin-left:10px;font-size:12px">
                    {{scope.option.bankName}}
                  </span>
                </div>
              </template>
            </filter-select>
          </el-form-item>
          <el-form-item required :label="costCustomerTypeText+'日期'">
            <el-date-picker v-model="costOrderForm.actualDay" class="form-input" type="datetime" value-format="timestamp" :editable="false" :picker-options="actualDateOption">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="开票金额">
            <el-input-number is-decimal-zero v-model="costOrderForm.invoicePrice" class="cost-input" :min="0" :precision="4" :controls="false"
              placeholder="请输入开票金额"></el-input-number>
          </el-form-item>
          <el-form-item label="开票日期">
            <el-date-picker v-model="costOrderForm.invoiceDate" class="cost-input" value-format="timestamp" :editable="false" :picker-options="dateOption"
              placeholder="请选择开票日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="costOrderForm.reason" class="cost-input" type="textarea" resize="none" :autosize="{minRows:3}" placeholder="请输入备注">
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <div style="text-align:center">
        <el-button type="primary" @click="toPayment(1)">{{costTypeText}}</el-button>
        <el-button type="primary" :disabled="!hasApproval" style="margin-left:0" @click="toPayment(2)">审核过账</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    computed: {
      costTypeText: function () {
        var type = this.costOrderForm.type;
        return type === 1 ? '收款' : '付款';
      },
      costCustomerTypeText: function () {
        var type = this.costOrderForm.type;
        return type === 1 ? '付款' : '收款';
      }
    },

    data: function () {
      var self = this;
      return {
        loading: false,
        payModeList: [],
        bankCardList: [],
        hasApproval: false,
        costOrderForm: new CostOrderForm(),
        typeList: i18n.getDropDown('warehouseBalance.detail.type', [1, 2]),
        showAddPayModeForm: false,
        customerNameList: [],
        providerNameList: [],
        dateOption: {
          disabledDate: function (time) {
            return !self.dateLimit(time);
          }
        },
        actualDateOption: {
          disabledDate: function (time) {
            return !self.dateLimit(time, 'second');
          }
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkApproval(),
        this.setPayModeList(),
        this.setBankCardList(),
        this.setCostNameList()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      checkApproval: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(11).then(function (hasApproval) {
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      setPayModeList: function () {
        var self = this;
        return ajaxRequest('warehouseInSumMoney/getPaymentModeList').then(function (payModeList) {
          payModeList = _.filter(payModeList, function (payMode) {
            return !SysUtil.isEmpty(payMode) && payMode.trim() !== '';
          });
          payModeList = _.uniq(payModeList);
          self.payModeList = payModeList;
          return payModeList;
        });
      },

      setBankCardList: function () {
        var self = this;
        return ajaxRequest('finance/getAllBank').then(function (bankCardList) {
          bankCardList = _.map(bankCardList, function (card) {
            return {
              num: card.bankCardNumber,
              bankName: card.bank
            };
          });
          self.bankCardList = bankCardList;
          return bankCardList;
        });
      },

      setCostNameList: function () {
        var dropdownOption = this.dropdownOption
        var customerNameList = dropdownOption.customerNameList;
        if (customerNameList !== undefined) {
          this.customerNameList = customerNameList;
          var providerNameList = dropdownOption.providerNameList;
          this.providerNameList = providerNameList;
          return Promise.resolve({
            customerNameList: customerNameList,
            providerNameList: providerNameList
          });
        }

        var self = this;
        return ajaxRequest('basicData/queryCustomersTow', {}, false).then(function (res) {
          var list = res.returnData;
          var customerNameList = [],
            providerNameList = [];
          for (var i = 0; i < list.length; i++) {
            var obj = list[i];
            var type = obj.type;
            if ([1, 3].indexOf(type) !== -1) {
              providerNameList.push(obj.customerName);
            }
            if ([2, 3].indexOf(type) !== -1) {
              customerNameList.push(obj.customerName);
            }
          }
          self.customerNameList = customerNameList;
          self.providerNameList = providerNameList;
          dropdownOption.customerNameList = customerNameList;
          dropdownOption.providerNameList = providerNameList;
          return {
            customerNameList: customerNameList,
            providerNameList: providerNameList
          };
        });
      },

      cardFilterMehod: function (query, option) {
        if (query === '') {
          return true;
        }
        query = query.toLowerCase();

        var num = option.num;
        num = num.toLowerCase();
        var bankName = option.bankName;
        bankName = bankName.toLowerCase();
        return num.indexOf(query) !== -1 || bankName.indexOf(query) !== -1;
      },

      addPayMode: function (payMode) {
        this.payModeList.push(payMode);
        this.costOrderForm.receiptPaymentMode = payMode;
        this.showAddPayModeForm = false;
      },

      clearInfo: function () {
        this.costOrderForm.clearInfo();
      },

      dateLimit: function (time, type) {
        if (type === undefined) {
          type = 'day';
        }
        return moment(time).isSameOrBefore(moment(), type);
      },

      toPayment: function (payType) {
        var costOrderForm = this.costOrderForm;
        var code = costOrderForm.checkValid();
        if (code !== '') {
          var type = costOrderForm.type;
          var msgtype = type === 1 ? 'outBalance.error' : 'warehouseBalance.error';
          var msg = i18n.getMsg(`${msgtype}.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        var postData = costOrderForm.getObject(payType);
        this.loading = true;
        var self = this;
        ajaxRequest('warehouseInSumMoney/saveReceiptPaymentRecord', {
          jsonObject: JSON.stringify(postData)
        }).then(function () {
          self.loading = false;
          self.$alert(`${self.costTypeText}成功`, '信息', {
            callback: function () {
              self.$emit('cost-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      AddPayModeForm: AddPayModeForm,
      FilterSelect: FilterSelect
    },

    template: template
  };
}();
